//
//  TreeView.m
//  CarLife
//
//  Created by yu on 2019/9/23.
//  Copyright © 2019 jpas. All rights reserved.
//

#import "TreeView.h"
#import "DepartmentModel.h"

@interface TreeView ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) DepartmentModel *dModel;

@property (assign, nonatomic) NSIndexPath *selectIndex;// 当前选中的行
@property (assign, nonatomic) NSIndexPath *tempIndex;// 实际选中的行

@end

@implementation TreeView

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.backgroundColor = kBackgroundColor;
        [self setupUI];
    }
    return self;
}

- (void)setupUI {
    
    _tempIndex = [NSIndexPath indexPathForRow:0 inSection:0];
    _selectIndex = _tempIndex;
    
    self.tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStyleGrouped];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self addSubview:self.tableView];
    
    UIButton *cancelBtn = [[UIButton alloc] init];
    [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
    [cancelBtn setBackgroundColor:[UIColor whiteColor]];
    [cancelBtn setTitleColor:kTextBlackColor forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancelAction) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:cancelBtn];
    
    UIButton *confirmBtn = [[UIButton alloc] init];
    [confirmBtn setTitle:@"确定" forState:UIControlStateNormal];
    [confirmBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [confirmBtn setBackgroundColor:kBaseColor];
    [confirmBtn addTarget:self action:@selector(confirmAction) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:confirmBtn];
    
    // 刘海屏平分控件宽度不好使！
//    self.sd_equalWidthSubviews = @[cancelBtn,confirmBtn];
    
    cancelBtn.sd_layout
    .leftEqualToView(self)
    .widthIs(kScreenWidth / 2)
    .bottomSpaceToView(self, kSafeAreaBottomHeight)
    .heightIs(40);
    
    confirmBtn.sd_layout
    .leftEqualToView(cancelBtn)
    .rightEqualToView(self)
    .widthIs(kScreenWidth / 2)
    .bottomEqualToView(cancelBtn)
    .heightRatioToView(cancelBtn, 1);
    
    self.tableView.sd_layout
    .leftEqualToView(self)
    .rightEqualToView(self)
    .topEqualToView(self)
    .bottomSpaceToView(cancelBtn, 0);
}

- (void)cancelAction {
    if (self.cancelBlock) {
        self.cancelBlock();
    }
}

- (void)confirmAction {
    _selectIndex = _tempIndex;
    if (self.confirmBlock) {
        self.confirmBlock(self.dModel);
    }
}

- (void)updateSelectStatus
{
    _tempIndex = _selectIndex;
    
    dispatch_async(dispatch_get_main_queue(), ^{
//        [self.tableView setContentOffset:CGPointMake(0, 38) animated:NO];
//        PPLog(@"contentOffset = %lf",self.tableView.contentOffset.y);
        [self.tableView reloadData];
        [self.tableView selectRowAtIndexPath:_tempIndex animated:NO scrollPosition:UITableViewScrollPositionNone];
        [self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:_tempIndex.row inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];
//        CGRect rect = [self.tableView rectForRowAtIndexPath:[NSIndexPath indexPathForRow:_tempIndex.row inSection:0]];
//        [self refreshContenOffset:rect];
        [self tableView:self.tableView didSelectRowAtIndexPath:_tempIndex];
    });
}

- (void)refreshContenOffset:(CGRect)rect {
//    CGRect frame = item.frame;
    CGFloat itemY = rect.origin.y;
    CGFloat height = self.tableView.frame.size.height;
    PPLog(@"height = %lf",height);
    CGSize contentSize = self.tableView.contentSize;
    if (itemY < height/2) {
        CGFloat targetY;
        if ((contentSize.height-itemY) <= height/2) {
            targetY = contentSize.height - height;
        } else {
            targetY = rect.origin.y - height/2 + rect.size.width/2;
        }
        if (targetY + height > contentSize.height) {
            targetY = contentSize.height - height;
        }
        [self.tableView setContentOffset:CGPointMake(0, targetY) animated:YES];
    } else {
        [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    }
}
// 让选中的item位于中间
//- (void)refreshContenOffset:(UIButton *)item {
//    CGRect frame = item.frame;
//    CGFloat itemY = frame.origin.y;
//    CGFloat height = self.tableView.frame.size.height;
//    CGSize contentSize = self.tableView.contentSize;
//    if (itemY > height/2) {
//        CGFloat targetY;
//        if ((contentSize.height-itemY) <= height/2) {
//            targetY = contentSize.height - height;
//        } else {
//            targetY = frame.origin.y - height/2 + frame.size.width/2;
//        }
//        if (targetY + height > contentSize.height) {
//            targetY = contentSize.height - height;
//        }
//        [self.tableView setContentOffset:CGPointMake(targetY, 0) animated:YES];
//    } else {
//        [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
//    }
//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.deptArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 38.;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"ListAccountCellIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.backgroundColor = kBackgroundColor;
        cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    }
    
    if (_tempIndex == indexPath) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;
    }else {
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    DepartmentModel *dModel = self.deptArray[indexPath.row];
    cell.textLabel.text = dModel.deptName;
    cell.indentationLevel = dModel.level - 1; // 缩进级别
    cell.indentationWidth = 18.; // 每个缩进级别的距离
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *celled = [tableView cellForRowAtIndexPath:_tempIndex];
    celled.accessoryType = UITableViewCellAccessoryNone;

    _tempIndex = indexPath;

    _dModel = self.deptArray[indexPath.row];
    
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryCheckmark;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UILabel *transferLabel = [[UILabel alloc] init];
    transferLabel.text = @"    请选择切换的账户";
    transferLabel.textColor = kTextLightBlackColor;
    transferLabel.font = SYSTEM_FONT(15);
    return transferLabel;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 35.;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.0001;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    return [UIView new];
}

//- (void)scrollViewDidScroll:(UIScrollView *)scrollView
//{
//    if (scrollView.contentOffset.y >= 0 && scrollView.contentOffset.y <= 35.) {
//        scrollView.contentInset = UIEdgeInsetsMake(-scrollView.contentOffset.y, 0, 0, 0);
//    }else if (scrollView.contentOffset.y >= 35.){
//        scrollView.contentInset = UIEdgeInsetsMake(-35., 0, 0, 0);
//    }
//}


@end
